package com.liming.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 天行数据API接口
 * 具体参数www.tianapi.com
 * 
 */
public class TianAPIUtil {
	// 天行数据 申请的 APIKEY
	private static final String key = "";
	
	// 雷人笑话
	public static final String JOKE = "http://api.tianapi.com/txapi/joke/";
	// 历史今天
	public static final String LISHI = "http://api.tianapi.com/txapi/lishi/";
	// 神回复
	public static final String GODREPLY = "http://api.tianapi.com/txapi/godreply/";
	// 股市术语
	public static final String SHARES = "http://api.tianapi.com/txapi/shares/";
	// 名言警句
	public static final String DICTUM = "http://api.tianapi.com/txapi/dictum/";

	// 美女图片
	public static final String MEINV = "http://api.tianapi.com/meinv/";
	// IT资讯
	public static final String IT = "http://api.tianapi.com/it/";
	
	public static void main(String[] args) throws JSONException {

		TianAPIUtil tianAPI = new TianAPIUtil();
		
		JSONArray jsonArray = tianAPI.request(tianAPI.MEINV, "&num=2");
		JSONObject jsonObject = null;
		
		for (int i=0; i<jsonArray.length();i++) {
			jsonObject = jsonArray.getJSONObject(i);
			System.out.println(jsonObject.getString("title")+"："+jsonObject.getString("picUrl"));
		}
	}

	/**
	 * @param httpUrl
	 *            :请求接口 示例：http://api.tianapi.com/txapi/meinv/
	 * @param httpArg
	 *            :参数 如：&num=1
	 * @return 返回结果
	 */
	public JSONArray request(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?key=" + key + httpArg;

		HttpURLConnection connection = null;
		try {
			URL url = new URL(httpUrl);
			connection = (HttpURLConnection) url.openConnection();
			// 建立连接
			connection.connect();
			int code = connection.getResponseCode();
			if (code == 200) {
				// connection.setRequestMethod("GET");
				InputStream is = connection.getInputStream();
				// 封装输入流
				reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String strRead = null;

				while ((strRead = reader.readLine()) != null) {
					sbf.append(strRead);
					sbf.append("\r\n");
				}
				// 关闭输入流
				reader.close();
				result = sbf.toString();
				if (result.length() == 0) {
					return null;
				}
				// 数据处理,这里需要获取newslist中的JSON
				JSONArray jsonArray = DateDisposeUtil.getJsonResult(result, "newslist");

				return jsonArray;			
			} else {
				System.out.println("code:" + code);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect(); // 关闭连接
			}
		}
		return null;
	}

}
